package com.module.product.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;

import base.common.CUDEnum;
import base.dao.GenericHibernateDao;
import base.util.Page;
import base.util.StringUtil;

import com.module.product.common.ProductConstant;
import com.module.product.vo.AttrValue;
import com.module.product.vo.Category;
import com.module.product.vo.Product;
import com.util.PropertiesUtil;
/**
*
* 商品dao类
*
* @author  王勇云
* @version  [V1.0, Jul 22, 2011]
* @see  [相关类/方法]
* @since  [二代服务平台/商品]
*/
public class ProductDao extends GenericHibernateDao<Product,String>{
	private static final ProductDao instance = new ProductDao();
	
	private String downloadPath = PropertiesUtil.getString("downloadPath");
	
	private String downloadHostName = PropertiesUtil.getString("downloadHostName");
	
	private int downloadPort = Integer.parseInt(PropertiesUtil.getString("downloadPort"));
	
	private ProductDao(){}
	
	public synchronized static ProductDao getInstance(){
		return instance;
	}
	   /**
     * <逻辑删除>
     * <功能详细描述>
     * @param attrGroup
     * @return
     * @see [类、类#方法、类#成员]
     */
    public boolean deleteObjs(Session session,Product obj){

        boolean flag = false;
        try {
            String hql = "update Product set updaterId = ?,updateTime=?,status =? where id in ("+obj.getId()+")";
            Query query  = session.createQuery(hql); 
                  query.setParameter(0,obj.getUpdaterId());
                  query.setParameter(1, new Date());
                  query.setParameter(2, CUDEnum.D.toString());
                  int i  = query.executeUpdate();
            flag = true;
            return flag;
        } catch (Exception ex) {
            ex.printStackTrace();
            return flag;
        }
    }

    /**
     * <通过企业查找商品>
     * @param obj
     * @return
     * @see [类、类#方法、类#成员]
     */
    public List<Product> findProductListbyOrgId(Session session,Product obj){
        List<Product> list = null;
        String hql = "from Product where status !='D' and orgId in ("+obj.getOrgId()+")";
        Query query = session.createQuery(hql);
        list = query.list();      
        return list;
    }
    /**
     * 查询属于属性组的产品数量
     * @param session
     * @param attrGroupId
     * @return
     */
    public long getCountByAttrGrop(Session session,String attrGroupId){
    	String hql = "select count(*) from Product where status <> ? and attrGroupId in ("+attrGroupId+") ";
    	Query query = session.createQuery(hql);
    	query.setParameter(0,  CUDEnum.D.toString());
    	return (long) ((Long) query.uniqueResult()).intValue();
    }
    
    public Page getList(Session session,Product obj,Page page){
        String hql1 = "from Product as obj where obj.status !='D' ";
        String hql2 = "select count(*) from Product as obj  where obj.status !='D' ";
        if(StringUtils.isNotBlank(obj.getName())){
            hql1=hql1 +  " and obj.name like '%"+obj.getName()+"%'";
            hql2=hql2 +  " and obj.name like '%"+obj.getName()+"%'";
        }
        if(StringUtils.isNotBlank(obj.getOrgName())){
            hql1=hql1 +  " and obj.orgName like '%"+obj.getOrgName()+"%'";
            hql2=hql2 +  " and obj.orgName like '%"+obj.getOrgName()+"%'";
        }
        if(StringUtils.isNotBlank(obj.getDesc())){
            hql1=hql1 +  " and obj.desc like '%"+obj.getDesc()+"%'";
            hql2=hql2 +  " and obj.desc like '%"+obj.getDesc()+"%'";
        }
        
        if(StringUtils.isNotBlank(obj.getOrgIds())){
            hql1=hql1 +  " and obj.orgId in ("+obj.getOrgIds()+")";
            hql2=hql2 +  " and obj.orgId in ("+obj.getOrgIds()+")";
        }     
        hql1 += " order by createTime desc";
        Query query = session.createQuery(hql1);
              query.setFirstResult(page.getStart()).setMaxResults(page.getLimit());
        
        page.setTotal((long) ((Long) session.createQuery(hql2)
        		.uniqueResult()).intValue());
        page.setRows(query.list());
        return page;
    }
    
    
    public boolean saveCategoryIdandProductId(Session session,Connection conn,String categoryId ,String productId){
        boolean b = false;
        try
        {
            String sql = " insert into p_category_product(category_id,product_id) values(?,?) ";
            PreparedStatement stmt = conn.prepareStatement(sql);
                              stmt.setString(1,categoryId);
                              stmt.setString(2,productId);
            stmt.execute();
            b = true ;
            return b;
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return b;
        } 

    }
    
    
    public List<String> findCategoryIdbyProductId(Session session,Connection conn,String productId) throws SQLException{
        List<String> list  = new ArrayList<String>();


	        String sql = "select category_id from p_category_product where product_id = ?";
	        PreparedStatement stmt = conn.prepareStatement(sql);
	                          stmt.setString(1,productId);
	        ResultSet rs  = stmt.executeQuery();  
	        //目前只做 一个商品属于一个分类
	        while(rs.next()){ 
	            list.add(rs.getString(1));
	           }                  

        return list;
    }
    
    /**
     * <一句话功能简述>
     * <功能详细描述>
     * @param productId
     * @return
     * @throws SQLException 
     * @see [类、类#方法、类#成员]
     */
    public List<Category> findCategoryListbyProductId(Session session,Connection conn,String productId) throws SQLException{
        List<Category> list  = new ArrayList<Category>();

        Category c = null;

        String sql = "select a.c_id,a.c_name,a.c_pid,a.c_desc from p_category a,p_category_product b where a.c_id = b.category_id and b.product_id = ? ";
        PreparedStatement stmt = conn.prepareStatement(sql);
                          stmt.setString(1,productId);
        ResultSet rs  = stmt.executeQuery();  
        while(rs.next()){ 
            c = new Category();
            c.setId(rs.getString(1));
            c.setName(rs.getString(2));
            c.setPid(rs.getString(3));
            c.setDesc(rs.getString(4));
            list.add(c);
           }                  

        return list;
    }
    /**
     * 根据商品id删除种类
     * @param productId
     * @return
     */
    public boolean deleteAllCategorybyProductId(Session session,Connection conn,String productId){
        boolean b = false;

        try
        {

            String sql = " delete from p_category_product where product_id = ? ";
            PreparedStatement stmt = conn.prepareStatement(sql);
                              stmt.setString(1,productId);
            stmt.executeUpdate();
            b = true ;
            return b;
        }
        catch (SQLException e)
        {
            e.printStackTrace();
            return b;
        } 

    }

    public boolean decreaseProductStocks(Session session,List list){
        boolean b = false;
        try
        {
            for(Iterator it = list.iterator();it.hasNext();){
            	Map map = (Map)it.next();
            	String hql = "  from AttrValue as av where av.productId = ? and av.attrName=?";
                List<AttrValue> avlist = session.createQuery(hql).setParameter(0, map.get("productId")).setParameter(1, "库存").list();
                if(!avlist.isEmpty() && avlist.size()>0){
                	AttrValue av = avlist.get(0);
                	Integer value = Integer.parseInt(av.getAttrValue())-((Integer)map.get("quantity"));
                	av.setAttrValue(value+"");
                	session.update(av);
                }
            }            
            b = true ;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        } 
        return b;
    }

    /**
     * 通过商品ID获取相应的属性及视频，图片;
     * @param beanUnit
     * @return
     * @throws SQLException 
     */
    /*
	public boolean getProductAttrByProductId(Session session,Connection conn,ProductBeanUnit beanUnit) throws SQLException {
		boolean result = false;
		Statement stmt = null;
		ResultSet rs = null;
		Product product = null;
		List<String> picPathList = new ArrayList<String>();
        try {
        	product = get(session,beanUnit.getProductId());
        	if(product!=null){
        		String sqlProductAttr = "SELECT item.c_type type,val.c_attr_value attrVal FROM p_attr_item item,p_attr_value val WHERE item.c_id=val.c_attritem_id AND " +
        		"item.c_status!='D' AND val.c_product_id='"+product.getId()+"' AND (item.c_type='3' OR item.c_type='4')";
        		stmt = conn.createStatement();
        		rs = stmt.executeQuery(sqlProductAttr);
        		boolean isFirstVedio = true;
        		while(rs.next()){
        			String type = rs.getString("type");
        			//只放第一条视频;
        			if(ProductConstant.ATTR_TYPE_VEDIO.equals(type)){
        				if(isFirstVedio && !StringUtil.isNull(rs.getString("attrVal"))){
        					product.setVedioPath(ProductConstant.HTTP_MEET+downloadHostName+":"+downloadPort+downloadPath +rs.getString("attrVal"));
        					isFirstVedio = false;
        				}
        			}
        			//图片;
        			else if(ProductConstant.ATTR_TYPE_PICTURE.equals(type)
        					&& !StringUtil.isNull(rs.getString("attrVal"))){
        				picPathList.add(ProductConstant.HTTP_MEET+downloadHostName+":"+downloadPort+downloadPath +rs.getString("attrVal"));
        			}
        		}
        		product.setPicturePathList(picPathList);
        		beanUnit.setProduct(product);
        		result = true;
        	}
        } finally {
        	close(rs);
        	this.close(stmt);
        }
        return result;
	}
	*/
}
